<template>
	<view class="home">
		<view class="header-nav">
			<u-tabs
				:list="list"
				:is-scroll="false"
				:current="current"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.08)'
				}"
				:inactiveStyle="{
					color: '#888',
					transform: 'scale(1)'
				}"
				@change="tabsChangeHandler"
				font-size="20"
			></u-tabs>
		</view>
		<view class="content-nav">
			<u-skeleton v-if="loading" v-for="i in 3" :key="i" avatar title rows="4" :loading="true" :animate="true"></u-skeleton>
			<BlogItem v-for="item in blogList" :key="item._id" :item="item" @closeActionSheet="as_closeHandler" @updateBlog="updateBlog"></BlogItem>
		</view>
		<view class="load-more">
			<uni-load-more :status="loadMoreStatue"></uni-load-more>
		</view>

		<view class="edit-nav" @click="editClick">
			<text class="iconfont icon-edit"></text>
		</view>

		<view class="action-sheet">
			<u-action-sheet
				:actions="actionSheetList"
				:show="as_showState"
				round="10"
				:closeOnClickOverlay="true"
				:closeOnClickAction="true"
				cancelText="取消"
				@close="close"
				@select="as_selectHandler"
			></u-action-sheet>
		</view>
	</view>
</template>

<script>
import BlogItem from '@/components/BlogItem/BlogItem.vue';
import { tokenExpiredOrErrorHandler } from '@/utils/tool.js';
const blog = uniCloud.importObject('blogObj', { customUI: true });
const commentObj = uniCloud.importObject("blog-comment",{ customUI: true })
import { store } from '@/uni_modules/uni-id-pages/common/store.js';
export default {
	components: {
		BlogItem
	},
	data() {
		return {
			list: [
				{
					name: '最新'
				},
				{
					name: '热门'
				}
			],
			current: 0, // header tabs 标识
			loading: false, // 主页数据加载，控制骨架屏
			blogList: [],
			loadMoreStatue: 'more',
			actionSheetList: [
				{
					name: '修改',
					type: 'update'
				},
				{
					name: '删除',
					type: 'delete',
					color: 'red'
				}
			],
			as_showState: false,
			selectedBlogId: '',
			scroll: 0,
		};
	},
	async onLoad() {
		this.loading = true;
		await this.initData()
		this.checkHasLike()
		this.loading = false;
	},
	onShow() {
		this.checkHasLike()
		const scroll = this.scroll;
		uni.pageScrollTo({
			scrollTop: scroll,
			duration: 500
		});
	},
	onReachBottom() {
		if (this.loading) return;
		this.loadMoreStatue = 'loading';
		this.initData();
	},
	onPageScroll(e) {
		if(Math.abs(e.scrollTop - this.scroll) > 50){
			this.scroll = e.scrollTop;
		}
	},
	methods: {
		async checkHasLike(){
			const user_id = store.userInfo._id
			if(!user_id) {
				for(let i = 0,len = this.blogList.length; i < len; i++){
					this.$set(this.blogList[i],'hasLike',false)
				}
				return
			}
			if(!this.blogList.length) return
			for(let i = 0,len = this.blogList.length; i < len; i++){
				this.$set(this.blogList[i],'hasLike',false)
			}
			const blogIdList = this.blogList.map((item) => item._id);
			blog.getBlogLikeListById(blogIdList, user_id)
			.then(res => {
				res.forEach(i => {
					this.$set(this.blogList[i],'hasLike',true)
				})
			})
		},
		close() {
			this.as_showState = false;
		},
		as_closeHandler({ disableStatus, blogId, isOwner } = {}) {
			if (disableStatus && !isOwner) {
				this.actionSheetList[0].disabled = true;
			}
			if (!disableStatus) {
				this.actionSheetList.forEach((i) => (i.disabled = true));
			}
			if (blogId) {
				this.selectedBlogId = blogId;
			}
			this.as_showState = !this.as_showState;
		},
		as_selectHandler(e) {
			e.type === 'update' &&
				uni.navigateTo({
					url: `/pages-blog/edit/edit?id=${this.selectedBlogId}`
				});
			e.type === 'delete' && this.deleteBlog(this.selectedBlogId);
		},
		deleteBlog(blogId) {
			const scroll = this.scroll;
			uni.showLoading({
				title: '加载中...'
			});

			blog.removeArticleById(blogId)
				.then(async (res) => {
					console.log(res);
					uni.showToast({
						title: '删除成功',
						icon: 'none'
					});
					const index = this.blogList.findIndex(b => b._id == blogId)
					if(index == -1) return 
					this.blogList.splice(index,1)
				})
				.catch((err) => {
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		},
		async tabsChangeHandler(e) {
			this.current = e.index;
			this.blogList = [];
			this.loading = true;
			await this.initData();
			this.loading = false;
		},
		editClick() {
			uni.navigateTo({
				url: '/pages-blog/edit/edit'
			});
		},
		async initData(skip, limit) {
			try {
				const res = await blog.getAllArticleData(skip || this.blogList.length, this.current, limit || 5);
				if (!res.length || res.length < 5) {
					this.loadMoreStatue = 'noMore';
				}else{
					this.loadMoreStatue = 'more';
				}
				this.blogList = [...this.blogList, ...res];
			} catch (err) {
				// token 失效处理
				tokenExpiredOrErrorHandler(err) &&
					uni.reLaunch({
						url: '/pages/index/index'
					});
				// 首页加载错误处理
				return;
			}
		},
		updateBlog({ target, key, value, type }) {
			if(type){
				let field = ""
				switch(type){
					case "updateViewCount":
					field = "view_count"
					break
					case "updateLikeCount":
					field = "like_count"
					break
					case "updateCommentCount":
					field = "comment_count"
					break
				}
				const index = this.blogList.findIndex(blog => blog._id == value.article_id);
				if(index  == -1) return
				this.blogList[index][field] += value.val
				if(field == "like_count"){
					this.blogList[index].hasLike = value.val == 1 ? true :false
				}
			}else{
				const index = this.blogList.findIndex((blog) => blog._id == target._id);
				this.$set(this.blogList[index], key, value);
			}
		}
	}
};
</script>

<style scoped lang="scss"></style>
